import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
  notification,
  Modal,
  message,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './style.less';
import router from 'umi/router';

const UNI_SIZE = "large";
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const basePath = `${window.location.protocol}//${window.location.hostname}`;
function getFileUrl(fileName) {
  return `${basePath}/track/Uploads/temp/${fileName}`;
}

let timer = null;

export default
@connect(({ post, loading }) => ({
  submitting: loading.effects['post/create'],
  modalPayVisible: post.modalPayVisible,
  orderData: post.orderData,
}))
@Form.create()
class BasicForms extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      thumbUrl: '',
      openId: null,
      platform: 'desktop',
    };
  }

  componentDidMount() {
    this.props.dispatch({type: 'post/saveOrderData', payload: {}});
    timer = setInterval(()=>{
      this.refreshOrder();
    }, 1000);

    const WechatUA = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
    if(WechatUA) {
      // 微信浏览器
      const openId = window.location.href.split('?openid=')[1];
      if (!openId) {
        window.location.href = `${basePath}/track/index.php/Post/wechat`;
      } else {
        this.setState({openId, platform: 'wechat'});
        console.log('openid:', openId);
      }
    }
  }

  componentWillUnmount() {
    clearInterval(timer);
    timer = null;
    this.setState({openId: null});
  }

  onBridgeReady = () => {
    const {orderData, dispatch} = this.props;
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', orderData.data,
      (res) => {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          dispatch({type: 'post/checkOrder', payload: {id: orderData.id}});
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
          message.error('支付已取消');
          router.push('/list');
        } else {
          message.error('支付发生错误：' + res.err_desc + res.err_msg);
        }
        WeixinJSBridge.log(res.err_msg);
      }
    );
  }

  doPay = () => {
    if (typeof WeixinJSBridge == "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
      }
    } else {
      this.onBridgeReady();
    }
  }

  handleUploadThumb = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ uploadingThumb: true });
      return;
    }
    if (info.file.status === 'done') {
      const {response} = info.file;
      if(response.status === 1) {
        notification.success({message: response.info});
        this.setState({ thumbUrl: response.data.savename, uploadingThumb: false });
      } else {
        notification.error({message: response.info, description: response.data, duration: 10});
      }
      this.setState({ uploadingThumb: false });
    }
  }

  handleCancelPay = () => {
    this.props.dispatch({type: 'post/hideModal'});
    router.push('/list');
  }

  handleSubmit = e => {
    const { dispatch, form } = this.props;
    const {thumbUrl, openId, platform} = this.state;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if((values.post_redpacket_price - 0) < (values.post_redpacket_num - 0)) {
          notification.error({message: '红包金额必须大于红包个数'});
          return;
        }
        const params = {
          ...values,
          post_thumb_url: thumbUrl,
          post_type: '0',
          openId,
          platform
        }
        dispatch({
          type: 'post/create',
          payload: {
            data: params,
            callback: () => {
              this.doPay();
            }
          },
        });
      }
    });
  };

  refreshOrder = () => {
    const {orderData} = this.props;
    if(orderData.id) {
      this.props.dispatch({type: 'post/checkOrder', payload: {id: orderData.id}});
    }
  }

  render() {
    const { submitting, modalPayVisible, orderData } = this.props;
    const {thumbUrl, uploadingThumb} = this.state;
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const smallItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 6 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type={uploadingThumb ? 'loading' : 'plus'} />
        <div className="ant-upload-text">选择文件</div>
      </div>
    );

    const {protocol, hostname} = window.location;
    const uploadThumbUrl = `${protocol}//${hostname}/track/index.php/Post/uploadThumb`;

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label="主标题">
              {getFieldDecorator('post_title', {
                rules: [
                  {
                    required: true,
                    message: '请输入主标题',
                  },
                  {
                    max: 40,
                    message: '最多支持40个字符',
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="最多支持40个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="副标题">
              {getFieldDecorator('post_subtitle', {
                rules: [
                  {
                    required: true,
                    message: '请输入副标题',
                  },
                  {
                    max: 40,
                    message: '最多支持40个字符',
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="最多支持40个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="缩略图" help="转发消息时显示的缩略图">
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={uploadThumbUrl}
                onChange={this.handleUploadThumb}
              >
                {thumbUrl ? <img src={getFileUrl(thumbUrl)} className={styles.uploadImage} alt="avatar" /> : uploadButton}
              </Upload>
            </FormItem>
            <FormItem {...smallItemLayout} label="红包个数">
              {getFieldDecorator('post_redpacket_num', {
                default: 1,
                rules: [
                  {
                    required: true,
                    message: '请输入红包个数',
                  },
                ],
              })(<InputNumber min={1} max={100} size={UNI_SIZE} />)}
            </FormItem>
            <FormItem {...smallItemLayout} label="红包总金额" help="红包总金额必须大于红包个数">
              {getFieldDecorator('post_redpacket_price', {
                rules: [
                  {
                    required: true,
                    message: '请输入红包总金额',
                  },
                  {
                    pattern: /^[0-9]*[1-9][0-9]*$/,
                    message: '只能输入正整数'
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="只能输入正整数" addonAfter="元" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="领红包规则">
              <div>
                {getFieldDecorator('post_redpacket_rule', {
                  initialValue: '0',
                })(
                  <Radio.Group>
                    <Radio value="0">每个红包金额相等</Radio>
                    <Radio value="1">每个红包金额随机</Radio>
                  </Radio.Group>
                )}
              </div>
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button size="large" type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
        <Modal
          title="红包金额充值"
          visible={modalPayVisible}
          footer={null}
          width={300}
          onCancel={this.handleCancelPay}
          maskClosable={false}
        >
          <div style={{textAlign: 'center'}}>
            <img src={`data:image/png;base64,${orderData.src}`} alt="qrCode" />
            <p style={{marginTop: 10}}>请使用微信扫描二维码进行支付</p>
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
